<?php

namespace Admin\Controller;

use Common\Common\AdminController;
use Common\Top;
use Common\Utils;

class AgencyController extends AdminController
{


    public function index()
    {
//        $list = setEncrypt(297);
//        dump($list);exit;
        $name = trim(I('names'));
        $operatorId = session('operator_id');
        $state = Top::StateDeleted;
        $roleId = session('role_id');
        $this->operatorData = C('SHOW_OPERATOR_DATA');
        if (strpos($this->operatorData, $roleId) !== false) {
            $this->operatorList = M('operator')->where('id != 2')->field('id,display_name')->select();
            $this->oid = !empty(I('get.oid')) ? I('get.oid') : 0;
            $operatorId = $this->oid;
            $map['operator_id'] = $operatorId;

            if ($this->oid == 0) {
                $map['operator_id'] = array('not in', '0,2');
                $operatorId = implode(',', array_column($this->operatorList, 'id'));
            }

            $this->agencyTotalNum = M('agency')->where("state != '{$state}'")->where($map)->count();
        }

        if ($name) {
            $where = "operator_id in($operatorId) && name like '%%$name%%' && state != '{$state}'";
        } else {
            $where = "operator_id in($operatorId) && state != '{$state}'";
        }

        $list = Utils::pages('agency', $where, C('PAGE_SET'), $order = " id desc ");
        $this->assign('name', $name);
        $this->todayDate = date("Y-m-d 00:00:00", time());
        $this->info = $list['info'];
        $this->page = $list['page'];
        $this->display();
    }


    /**
     * 设置账号状态 - 禁用 冻结
     */
    public function setAccountStatus()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $state = I('post.state');
            $id = I('post.id', 0, 'int');

            $info = M('agency')->where("id = '{$id}'")->find();

            if ($state && $id) {
                $entityType = Top::EntityTypeAgency;
                $logData['operator_id'] = $info['operator_id'];
                $logData['user_id'] = session('user_id');
                $logData['user_name'] = session('entity_name');
                $logData['action'] = $logData['user_name'] . "禁用了代理商" . $info['name'] . "的账号";
                $logData['memo'] = I('memo');
                $logData['create_time'] = date("Y-m-d H:i:s", time());

                if ($state == Top::StateEnabled || $state == Top::StateDisabled) {
                    if ($state == Top::StateEnabled) {
                        $logData['action'] = $logData['user_name'] . "恢复了代理商" . $info['name'] . "的账号状态";
                    }

                    M('log_account_status')->add($logData);

                    if ($state == $info['state']) {
                        $data['status'] = 1;
                        $this->ajaxReturn($data);
                    }

                    $result = M('agency')->where("id = '{$id}'")->setField('state', $state);
                    M('user')->where("entity_id = '{$id}' && entity_type = '{$entityType}'")->setField('state', $state);
                } elseif ($state == 'freeze2' || $state == 'nofreeze1') {

                    if ($state == 'freeze2') {
                        $account_state = Top::StateDisabled;
                        $logData['action'] = $logData['user_name'] . "冻结了代理商" . $info['name'] . "的账户";
                    } elseif ($state == 'nofreeze1') {
                        $account_state = Top::StateEnabled;
                        $logData['action'] = $logData['user_name'] . "恢复了代理商" . $info['name'] . "的账户状态";
                    }

                    M('log_account_status')->add($logData);

                    if ($state == $info['account_state']) {
                        $data['status'] = 1;
                        $this->ajaxReturn($data);
                    }

                    $result = M('agency')->where("id = '{$id}'")->setField('account_state', $account_state);
                }

                if ($result) {
                    $data['status'] = 1;
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '操作失败';
                    $this->ajaxReturn($data);
                }
            } else {
                return false;
            }
        }
    }
    /**
     * 查询C客户对顾问的意见反馈列表（平台/运营商）
     */
    public function adviser_feedback(){
            $name = trim(I('names'));
        $operatorId = session('operator_id');
        $state = Top::StateDeleted;
        $roleId = session('role_id');

        $this->operatorData = C('SHOW_OPERATOR_DATA');

        if (strpos($this->operatorData, $roleId) !== false) {
            $this->operatorList = M('operator')->where('id != 2')->field('id,display_name')->select();
            $this->oid = !empty(I('get.oid')) ? I('get.oid') : 0;
            $operatorId = $this->oid;

            if ($this->oid == 0) {
                $operatorId = implode(',', array_column($this->operatorList, 'id'));
            }
        }

        if ($name) {
            $where = "operator_id in($operatorId) && comment_type = 0 && (cover_commnet_name like '%%$name%%')";
        } else {
            $where = "operator_id in($operatorId) && comment_type = 0 ";
        }


        $list = Utils::pages('feedback', $where, C('PAGE_SET'), $order = " id desc ");
        $this->assign('name', $name);
        $this->info = $list['info'];
        $this->page = $list['page'];
        $this->oper = M('operator')->field('id,name')->find(session('entity_id'));
        $this->display();
    }
    
        public function deleteAdviserFeedback()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $ids = I('action_code');
            $data['state'] = 1;
            M('feedback')->startTrans();
            try {
                foreach ($ids as $id) {
                    $id = Utils::getDecrypt($id);
                 
                    $result = M('feedback')->where("id = '{$id}'")->save($data);
                }

                if ($result) {
                    M('feedback')->commit();
                    $data['status'] = 1;
                    $data['msg'] = '删除成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '删除失败';
                    $this->ajaxReturn($data);
                }
            } catch (Exception $ex) {
                M('feedback')->rollback();
            }
        } else {
            $data['status'] = 2;
            $data['msg'] = '系统出错';
            $this->ajaxReturn($data);
        }
    }

    /**
     * 查看账户金额信息
     */
    public function showAgencyAccountInfo()
    {
        if (IS_POST && IS_AJAX) {
            $id = I('id');
            $agencyInfo = M('agency')->where("id = '{$id}'")->field('id,name,account_balance')->find();
            $entityType = Top::EntityTypeAgency;

            if ($agencyInfo) {
                $data['status'] = 1;
                $total = $agencyInfo['account_balance'];
                $frozenMoney = Utils::getFrozenFen($entityType, $id);
                $data['name'] = $agencyInfo['name'];
                $data['total'] = Utils::getYuan($total);
                $data['frozenMoney'] = Utils::getYuan($frozenMoney);
                $data['availableBalance'] = Utils::getYuan($total - $frozenMoney);
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['name'] = $agencyInfo['name'];
                $data['total'] = '0.00';
                $data['frozenMoney'] = '0.00';
                $data['availableBalance'] = '0.00';
                $this->ajaxReturn($data);
            }
        }
    }


    public function showTransaction()
    {
        if ($this->warnStatus == '10404') {
            $this->redirect("Error/index");
        }

        $entity_type = Top::EntityTypeAgency;
        $entity_id = I('get.aid');

        $agencyInfo = M('agency')->where("id = '{$entity_id}'")->field('id,operator_id')->find();
        $operatorId = $agencyInfo['operator_id'];

        $action = trim(I('entity_name'));
        $startTime = !empty(I('start_time')) ? I('start_time') : date("2015-05-01", time());
        $endTime = !empty(I('end_time')) ? I('end_time') : date('Y-m-d', time());

        $where = "operator_id = '{$operatorId}' && entity_type = '{$entity_type}' && entity_id = '{$entity_id}' && action like '%%$action%%' && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
        $pageInfo = Utils::pages('account_transaction', $where, C('TRANSACTION_PAGE_SET'), $order = " id desc ");

        foreach ($pageInfo['info'] as $key => $vo) {
            if ($vo['object_type'] == 1) {
                $pageInfo['info'][$key]['objectName']['tour_name'] = '充值';
            } else if ($vo['object_type'] == 2) {
                $pageInfo['info'][$key]['objectName']['tour_name'] = '提现';
            } else if ($vo['object_type'] == 3) {
                $pageInfo['info'][$key]['objectName'] = M('agency_invoice')->where("id = " . $vo['object_id'])->field('detail tour_name')->find();
            } else if ($vo['object_type'] == 4) {
                $pageInfo['info'][$key]['objectName']['tour_name'] = '合同';
            } else if ($vo['object_type'] == 5) {
                $pageInfo['info'][$key]['objectName'] = M('order_tour')->where("id = " . $vo['object_id'])->field('tour_name')->find();
            } else if ($vo['object_type'] == 6) {
                $pageInfo['info'][$key]['objectName'] = M('order_product')->where("id = " . $vo['object_id'])->field('product_name tour_name')->find();
            } else if ($vo['object_type'] == 7) {
                $pageInfo['info'][$key]['objectName']['tour_name'] = '机票';
            } else if ($vo['object_type'] == 8) {
                $pageInfo['info'][$key]['objectName']['tour_name'] = '账户调整';
            } else if ($vo['object_type'] == 9) {
                $pageInfo['info'][$key]['objectName']['tour_name'] = '门票';
            } else if ($vo['object_type'] == 11) {
                $pageInfo['info'][$key]['objectName']['tour_name'] = '扣除服务费';
            }
        }

        $total = M('account_transaction')->where($where)->field('count(id) totalNum, sum(amount) totalPrice')->select();

        $topUpTotal = M('account_transaction')->where("entity_type = '{$entity_type}' && entity_id = '{$entity_id}' && operator_id = '{$operatorId}' && object_type = 1")->field('sum(amount) topUpTotal')->select();
        $invoiceTotal = M('agency_invoice')->where("entity_type = '{$entity_type}' && entity_id = '{$entity_id}' && operator_id = '{$operatorId}' && state = 2")->field('sum(amount) invoicetotal')->select();
        $lastTotal = $topUpTotal[0]['topuptotal'] - abs($invoiceTotal[0]['invoicetotal']);
        $agencyInfo = M('agency')->where("id = '$entity_id'")->find();
        $name = $agencyInfo['name'];

        $this->info = $pageInfo['info'];
        $this->page = $pageInfo['page'];
        $this->assign('name', $name);
        $this->assign('sname', $action);
        $this->assign('startTime', $startTime);
        $this->assign('endTime', $endTime);
        $this->assign('total', $total);
        $this->assign('topUpTotal', $topUpTotal);
        $this->assign('invoiceTotal', $invoiceTotal);
        $this->assign('lastTotal', $lastTotal);
        $this->display();
    }

    /**
     * 设置/取消 测试账号
     */
    public function setAccount()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            $data['istest'] = I('state');
            $result = M('agency')->where($where)->save($data);

            if ($result) {
                $data['status'] = 1;
                $data['msg'] = '操作成功';
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }
        }
    }

//处理修改顾问密码处理
    public function editAgencyPwd()
    {
        $id = I('id');
        $keyid = Utils::getDecrypt(I('keyid'));

        if ($id != $keyid) {
            $data['status'] = 0;
            $data['msg'] = '修改失败';
            $this->ajaxReturn($data);
        }

        $user['entity_id'] = $id;
        $user['entity_type'] = Top::EntityTypeAgency;

        if (IS_AJAX && IS_POST) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $pwd = I('newpwd');
            $pwd = Utils::getHashPwd($pwd);
            $confirm_password = I('password2');
            $confirm_password = Utils::getHashPwd($confirm_password);

            if ($pwd != $confirm_password) {
                $data['status'] = 3;
                $data['msg'] = '两次密码不一致';
                $this->ajaxReturn($data);
            } else {
                $data['login_pwd'] = $pwd;
                $data['update_time'] = date('Y-m-d H:i:s', time());
                $result = M('user')->where($user)->save($data);

                if ($result) {
                    $data['status'] = 1;
                    $data['msg'] = '修改成功';
                    $this->ajaxReturn($data);
                }
            }
        }
    }
//扣除顾问服务费处理
    public function reduceServiceCharge()
    {
        $id = I('id');
        $keyid = Utils::getDecrypt(I('keyid'));

        if ($id != $keyid) {
            $data['status'] = 0;
            $data['msg'] = '修改失败';
            $this->ajaxReturn($data);
        }

       
        if (IS_AJAX && IS_POST) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }
            $server_money = I('server_money');
            $user_account = M('agency')->field('account_balance,operator_id,name')->where('id=' . $id)->find();
            $user_money = $user_account['account_balance']/100;
            if ($server_money > $user_money) {
                $data['status'] = 0;
                $data['msg'] = '该顾问余额不足，无法扣除';
                $this->ajaxReturn($data);
            }

            $data['service_name'] =  I('server_name');
            $data['service_money'] = Utils::getFen($server_money);
            $data['operator_id'] = $user_account['operator_id'];
            $data['entity_name'] = $user_account['name'];
            $data['entity_id'] = $id;
            $data['entity_type'] = Top::EntityTypeAgency;
            $data['create_time'] = date('Y-m-d H:i:s', time());
            $data['state'] = 0;
            $result = M('service_charge')->add($data);
            if ($result) {
                $data['status'] = 1;
                $data['msg'] = '扣除生成，待顾问确认';
                $this->ajaxReturn($data);
            }
        }
    }
    //扣除代理商服务费列表
    public function serviceChargeList(){
          $_SESSION['topUpCode'] = 400;
        $name = trim(I('names'));
        $operatorId = session('operator_id');
        $roleId = session('role_id');
        $entity_type = Top::EntityTypeAgency;
        $startTime = !empty(I('start_time')) ? I('start_time') : date("2015-05-01", time());
        $endTime = !empty(I('end_time')) ? I('end_time') : date('Y-m-d', time());

        $this->operatorData = C('SHOW_OPERATOR_DATA');
        if (strpos($this->operatorData, $roleId) !== false) {
            $this->operatorList = M('operator')->where('id != 2')->field('id,display_name')->select();
            $this->oid = !empty(I('get.oid')) ? I('get.oid') : 0;
            $operatorId = $this->oid;

            if ($this->oid == 0) {
                $operatorId = implode(',', array_column($this->operatorList, 'id'));
            }
        }

        if (!empty($name) || !empty($startTime) || !empty($endTime)) {
            $where = "operator_id in($operatorId) && entity_type = '{$entity_type}' && entity_name like '%%$name%%' && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
        }
        $pageInfo = Utils::pages('service_charge', $where, C('PAGE_SET'), $order = " id desc ");

//        dump($pageInfo['info']);exit;
        $this->info = $pageInfo['info'];
        $this->page = $pageInfo['page'];
        $this->assign('name', $name);
        $this->assign('startTime', $startTime);
        $this->assign('endTime', $endTime);
        $this->display();
    }


    public function resetAgencyOpenId()
    {
        if (IS_AJAX && IS_POST) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            $data['weixinmp_openid'] = '';
            $info = M('agency')->where($where)->field('weixinmp_openid')->find();
            $weixinmpOpenId = $info['weixinmp_openid'];

            if (!$weixinmpOpenId) {
                $data['status'] = 1;
                $data['msg'] = '操作成功';
                $this->ajaxReturn($data);
            }

            $result = M('agency')->where($where)->save($data);

            if ($result) {
                $data['status'] = 1;
                $data['msg'] = '操作成功';
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }
        }
    }


    public function checkDomain()
    {
        if (IS_POST && IS_AJAX) {
            $domain = I('domain');
            $where['domain'] = $domain;
            $agencyInfo = M('agency')->where($where)->find();

            if ($agencyInfo) {
                $newDomain = substr($domain, 0, strpos($domain, ".")) . time() . ".m.dalvu.com";
                $data['domain'] = $newDomain;
                $data['status'] = 1;
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $this->ajaxReturn($data);
            }
        }
    }


    public function add()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $mobile = I('telphone');
            $domain = I('domain');
            $pwd = I('login_pwd');
            $login_name = I('login_name');
            $operatorId = session('operator_id');
            $user = M('user')->where("login_name = '{$login_name}'")->find();
            $agency = M('agency')->where("mobile = '{$mobile}' || domain like '%%$domain%%'")->find();

            M('agency')->startTrans();
            try {
                if (!$user && !$agency) {
                    $data['domain'] = $domain;
                    $data['mobile'] = $mobile;
                    $data['name'] = I('name');
                    $data['vocation'] = I('vocation');
                    $data['account'] = Utils::getNextAccount(Top::EntityTypeAgency, $operatorId);
                    $data['operator_id'] = $operatorId;
                    $data['state'] = Top::StateEnabled;
                    $data['account_state'] = Top::StateEnabled;
                    $data['login_time'] = date('Y-m-d H:i:s', time());
                    $data['create_time'] = date('Y-m-d H:i:s', time());
                    $agencyId = M('agency')->add($data);

                    $user_data['name'] = I('name');
                    $user_data['role_id'] = 0;
                    $user_data['is_admin'] = 1;
                    $user_data['entity_type'] = Top::EntityTypeAgency;
                    $user_data['entity_id'] = $agencyId;
                    $user_data['login_name'] = $login_name;
                    $user_data['login_pwd'] = Utils::getHashPwd($pwd);
                    $user_data['mobile'] = $mobile;
                    $user_data['create_time'] = date('Y-m-d H:i:s', time());
                    $user_data['state'] = Top::StateEnabled;
                    $userId = M('user')->add($user_data);

                    if ($agencyId && $userId) {
                        M('agency')->commit();
                        $data['status'] = 1;
                        $data['msg'] = '操作成功';
                        $this->ajaxReturn($data);
                    }
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '该代理商信息已存在，不可用';
                    $this->ajaxReturn($data);
                }
            } catch (Exception $ex) {
                M('agency')->rollback();
            }
        }
    }


    public function delete()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $ids = I('action_code');
            $operatorId = session('operator_id');
            $entityType = Top::EntityTypeAgency;
            $data['state'] = Top::StateDeleted;

            M('agency')->startTrans();
            try {
                foreach ($ids as $id) {
                    $id = Utils::getDecrypt($id);
                    $result = M('agency')->where("id = '{$id}' && operator_id = '{$operatorId}'")->save($data);
                    $userResult = M('user')->where("entity_type = '{$entityType}' && entity_id = '{$id}'")->save($data);
                }

                if ($result && $userResult) {
                    M('agency')->commit();
                    $data['status'] = 1;
                    $data['msg'] = '删除成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '删除失败';
                    $this->ajaxReturn($data);
                }
            } catch (Exception $ex) {
                M('agency')->rollback();
            }
        }
    }


    public function edit()
    {
         
        if (IS_POST && IS_AJAX) {
           if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }
            $id = I('id', 0, 'int');
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '修改失败';
                $this->ajaxReturn($data);
            }

            $agencyInfo = M('agency')->where("id = '{$id}'")->find();
            $agency_data['operator_id'] = $agencyInfo['operator_id'];
            $agency_data['mobile'] = I('telphone');
            $agency_data['email'] = I('email');
            $agency_data['bank_account'] = I('bank_account');
            $agency_data['bank_name'] = I('bank_name');
            $agency_data['qq'] = I('qq');
            $agency_data['domain'] = I('domain');
            $agency_data['client_manager'] = I('client_manager');
            $agency_data['vocation'] = I('vocation');
            $agency_data['contract_start_time'] = !empty(I('contract_start_time')) ? I('contract_start_time') : '0000-00-00 00:00:00';
            $agency_data['contract_end_time'] = !empty(I('contract_end_time')) ? I('contract_end_time') : '0000-00-00 00:00:00';
            $agency_data['update_time'] = date('Y-m-d H:i:s', time());

            $data['entity_type'] = Top::EntityTypeAgency;
            $data['mobile'] = I('telphone');
            $data['is_admin'] = 1;
            $data['login_name'] = I('login_name');
            $data['update_time'] = date('Y-m-d H:i:s', time());

            $domain = $agency_data['domain'];
            $result = M('agency')->where("id != '{$id}' && (domain = '{$domain}' || mobile = '{$data['mobile']}')")->find();

            $login_name = $data['login_name'];
            $userResult = M('user')->where("entity_id != '{$id}' && login_name = '{$login_name}'")->field('id')->find();

            if ($userResult || $result) {
                $data['status'] = 2;
                $data['msg'] = '您输入的信息已存在，请重新输入！';
                $this->ajaxReturn($data);
            } else {
                M('agency')->where('id=' . $id)->save($agency_data);
                $where['entity_id'] = $agencyInfo['id'];
                $where['entity_type'] = Top::EntityTypeAgency;

                M('user')->where($where)->save($data);
                $data['status'] = 1;
                $data['msg'] = '修改成功';
                $this->ajaxReturn($data);
            }
        } else {
            $id = I('aid', 0, 'int');
            $agencyInfo = M('agency')->where("id='{$id}'")->find();
            $data['entity_id'] = $agencyInfo['id'];
            $data['entity_type'] = Top::EntityTypeAgency;
            $userInfo = M('user')->where($data)->find();

            $this->assign('list', $agencyInfo);
            $this->assign('user_list', $userInfo);
            $this->display();
        }
    }


    public function seniorEdit()
    {
        if ($this->warnStatus == '10404') {
            $data['status'] = 2;
            $data['msg'] = $this->warnInfo;
            $this->ajaxreturn($data);
        }

        $id = I('id');
        $keyid = Utils::getDecrypt(I('keyid'));

        if ($id != $keyid) {
            $data['status'] = 0;
            $data['msg'] = '操作失败';
            $this->ajaxReturn($data);
        }

        $data['name'] = I('real_name');
        $data['idcard_type'] = I('identity_type');
        $data['idcard'] = I('identity_num');

        M('agency')->startTrans();
        try {
            $result = M('agency')->where("id = '{$id}'")->save($data);

            $entityType = Top::EntityTypeAgency;
            $userData['name'] = I('real_name');
            M('user')->where("entity_id = '{$id}' && entity_type = '{$entityType}'")->save($userData);

            if ($result) {
                M('agency')->commit();
                $data['status'] = 1;
                $data['msg'] = '操作成功';
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }
        } catch (Exception $ex) {
            M('agency')->rollback();
        }
    }

    /**
     * 审核充值申请
     */
    public function auditTopUp()
    {
        if (IS_AJAX && IS_POST) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            $state = I('state');
            $data['memo'] = I('memo');
            $data['state'] = $state;
            $data['update_time'] = date('Y-m-d H:i:s', time());
            $data['entity_type'] = Top::EntityTypeAgency;
            $data['operator_id'] = session('operator_id');
            $data['proof_type'] = I('proof_type');
            $data['proof_code'] = I('proof_code');

            $topUpInfo = M('account_topup')->where($where)->find();
            $agencyId['id'] = $topUpInfo['entity_id'];
            $agencyInfo = M('agency')->where($agencyId)->find();

            if ($agencyInfo['state'] != 1) {
                $data['status'] = 5;
                $data['msg'] = '代理商账户被禁用';
                $this->ajaxReturn($data);
            }

            $topupType = $topUpInfo['topup_type'];

            if ($topupType == '1') {
                $topupType = '现金充值';
            } else if ($topupType == '2') {
                $topupType = '刷卡充值';
            } else if ($topupType == '3') {
                $topupType = '支票充值';
            } else if ($topupType == '4') {
                $topupType = '银行转账';
            } else if ($topupType == '5') {
                $topupType = '支付宝转账';
            }

            if ($state == Top::ApplyStateReject) {
                $result = M('account_topup')->where($where)->save($data);

                $template = array(
                    'touser' => $agencyInfo['weixinmp_openid'],
                    'template_id' => Utils::topUpTemplateId(),

                    'data' => array(
                        'first' => array('value' => urlencode("亲,您的充值申请于 " . $data['update_time'] . " 未通过审核,充值失败"), 'color' => "#000"),
                        'keyword1' => array('value' => urlencode($topUpInfo['entity_name']), 'color' => "#000"),
                        'keyword2' => array('value' => urlencode(Utils::getYuan($topUpInfo['amount'])), 'color' => '#000'),
                        'keyword3' => array('value' => urlencode($topUpInfo['create_time']), 'color' => '#000'),
                        'remark' => array('value' => urlencode("充值类型: $topupType"), 'color' => '#000'),
                    )
                );
                $this->send_tpl($template);

                if ($result) {
                    $data['status'] = 1;
                    $data['msg'] = '操作成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 2;
                    $data['msg'] = '操作失败';
                    $this->ajaxReturn($data);
                }
            }


            $postCode = I('code');
            $code = session('topUpCode');

            if ($code == $postCode) {
                if ($state == Top::ApplyStatePass) {
                    M('agency')->startTrans();
                    try {
                        session('topUpCode', null);

                        $result = M('account_topup')->where($where)->save($data);
                        $agencyResult = M('agency')->where($agencyId)->setInc('account_balance', $topUpInfo['amount']);
                        $agency_list = M('agency')->where($agencyId)->find();

                        $transaction_data['operator_id'] = session('operator_id');
                        $transaction_data['action'] = '充值';
                        $transaction_data['entity_type'] = Top::EntityTypeAgency;
                        $transaction_data['entity_id'] = $agency_list['id'];
                        $transaction_data['account'] = $agency_list['account'];
                        $transaction_data['amount'] = $topUpInfo['amount'];
                        $transaction_data['sn'] = Utils::getSn();
                        $transaction_data['balance'] = $agency_list['account_balance'];
                        $transaction_data['create_time'] = date('Y-m-d H:i:s', time());
                        $transaction_data['remark'] = 'top_account_topup.id:' . I('id');
                        $transaction_data['object_id'] = I('id');
                        $transaction_data['object_type'] = Top::ObjectTypeTopUp;
                        $transaction_data['object_name'] = '充值';
                        $transactionId = M('account_transaction')->add($transaction_data);

                        $template = array(
                            'touser' => $agencyInfo['weixinmp_openid'],
                            'template_id' => Utils::topUpTemplateId(),

                            'data' => array(
                                'first' => array('value' => urlencode("亲,您的充值申请于 " . $data['update_time'] . " 通过审核,充值成功"), 'color' => "#000"),
                                'keyword1' => array('value' => urlencode($topUpInfo['entity_name']), 'color' => "#000"),
                                'keyword2' => array('value' => urlencode(Utils::getYuan($topUpInfo['amount'])), 'color' => '#000'),
                                'keyword3' => array('value' => urlencode($topUpInfo['create_time']), 'color' => '#000'),
                                'remark' => array('value' => urlencode("充值类型: $topupType"), 'color' => '#000'),
                            )
                        );

                        $createDate = I('create_time');
                        $policyInfo = M('promotion_policy')->find();
                        $activityFullDate = $policyInfo['start_date'];
                        $activityDate = date("Ymd", strtotime($activityFullDate));
                        $amount = (int)$topUpInfo['amount'];
                        $effectDate = "2015-11-11";
                        $expireDate = "2015-12-31";

                        //coupon
                        if ($createDate == $activityDate) {
                            if ($amount >= 2000000 && $amount < 3000000) {
                                $count = 1;
                            } else if ($amount >= 3000000 && $amount < 5000000) {
                                $count = 4;
                            } else if ($amount >= 5000000) {
                                $count = 10;
                            }

                            for ($i = 0; $i < $count; $i++) {
                                $dataArr[$i]['agency_id'] = $agency_list['id'];
                                $dataArr[$i]['effect_date'] = $effectDate;
                                $dataArr[$i]['expire_date'] = $expireDate;
                                $dataArr[$i]['filter'] = "code:芽庄,";
                                $dataArr[$i]['amount'] = 50000;
                                $dataArr[$i]['name'] = "北京康泰500元代金券";
                                $dataArr[$i]['type'] = 1;
                                $dataArr[$i]['state'] = Top::CouponStateNotUsed;
                                $dataArr[$i]['memo'] = I('id');
                                $dataArr[$i]['create_time'] = date('Y-m-d H:i:s', time());
                            }

                            $couponResult = M('promotion_coupon')->addAll($dataArr);
                        }

                        if ($result && $agencyResult && $transactionId) {
                            M('agency')->commit();
                            $this->send_tpl($template);
                            $data['status'] = 1;
                            $data['msg'] = '操作成功';
                            $this->ajaxReturn($data);
                        } else {
                            $data['status'] = 3;
                            $data['msg'] = '操作失败';
                            $this->ajaxReturn($data);
                        }
                    } catch (Exception $ex) {
                        M('agency')->rollback();
                    }
                }
            } else {
                $data['status'] = 4;
                $data['msg'] = '请勿重复提交';
                $this->ajaxReturn($data);
            }
        }
    }

    /**
     * 更新充值申请凭证
     */
    public function updateTopUpProof()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $state = I('state');
            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxreturn($data);
            }

            if ($state == 2 || $state == 3) {
                $data['proof_type'] = I('proof_type');
                $data['proof_code'] = I('proof_code');
                $result = M('account_topup')->where($where)->save($data);

                if ($result) {
                    $data['status'] = 1;
                    $data['msg'] = '操作成功';
                    $this->ajaxreturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '操作失败';
                    $this->ajaxreturn($data);
                }
            }
        }
    }

    /**
     * 更新提现申请凭证
     */
    public function updateWithDrawProof()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $state = I('state');
            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 2;
                $data['msg'] = '操作失败';
                $this->ajaxreturn($data);
            }

            if ($state == Top::ApplyStateFinish) {
                $data['proof_type'] = I('proof_type');
                $data['proof_code'] = I('proof_code');
                $result = M('account_withdraw')->where($where)->save($data);

                if ($result) {
                    $data['status'] = 1;
                    $data['msg'] = '操作成功';
                    $this->ajaxreturn($data);
                } else {
                    $data['status'] = 2;
                    $data['msg'] = '操作失败';
                    $this->ajaxreturn($data);
                }
            }
        }
    }

    /**
     * 代理商充值申请列表
     */
    public function topupList()
    {
        $_SESSION['topUpCode'] = 400;
        $name = trim(I('names'));
        $operatorId = session('operator_id');
        $roleId = session('role_id');
        $entity_type = Top::EntityTypeAgency;
        $startTime = !empty(I('start_time')) ? I('start_time') : date("2015-05-01", time());
        $endTime = !empty(I('end_time')) ? I('end_time') : date('Y-m-d', time());

        $this->operatorData = C('SHOW_OPERATOR_DATA');
        if (strpos($this->operatorData, $roleId) !== false) {
            $this->operatorList = M('operator')->where('id != 2')->field('id,display_name')->select();
            $this->oid = !empty(I('get.oid')) ? I('get.oid') : 0;
            $operatorId = $this->oid;

            if ($this->oid == 0) {
                $operatorId = implode(',', array_column($this->operatorList, 'id'));
            }
        }

        if (!empty($name) || !empty($startTime) || !empty($endTime)) {
            $where = "operator_id in($operatorId) && entity_type = '{$entity_type}' && entity_name like '%%$name%%' && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
        }
        $pageInfo = Utils::pages('account_topup', $where, C('PAGE_SET'), $order = " id desc ");
//        dump($pageInfo['info']);exit;
        $this->info = $pageInfo['info'];
        $this->page = $pageInfo['page'];
        $this->assign('name', $name);
        $this->assign('startTime', $startTime);
        $this->assign('endTime', $endTime);
        $this->display();
    }


    /**
     * 查看凭证信息
     */
    public function showProofInfo()
    {
        if (IS_POST && IS_AJAX) {
            $id['id'] = I('id');
            $type = I('type');

            if ($type == 1) {
                $table = 'account_topup';
            } else if ($type == 2) {
                $table = 'account_withdraw';
            } else if ($type == 3) {
                $table = 'agency_invoice';
            } else if ($type == 4) {
                $table = 'agency_contract';
            } else if ($type == 6) {
                $table = 'order_product';
            } else if ($type == 7) {
                $table = 'order_flight';
            } else if ($type == 8) {
                $table = 'order_ticket';
            } else if ($type == 5) {
                $table = 'operator_credit_topup';
            }

            $list = M($table)->where($id)->field('id,proof_code,proof_type')->find();
            $this->ajaxReturn($list);
        }
    }


    /**
     * 查看快递信息 - 发票 合同
     */
    public function showExpressInfo()
    {
        if (IS_POST && IS_AJAX) {
            $where['id'] = I('id');
            $type = I('type');

            if ($type == 3) {
                $table = 'agency_invoice';
            } else if ($type == 4) {
                $table = 'agency_contract';
            }

            $info = M($table)->where($where)->find();
            $express = explode(",", $info['express']);
            $contractAddr = explode(',', $info['addr']);
            $agencyInfo['contact_person'] = $contractAddr[0];
            $agencyInfo['contact_phone'] = $contractAddr[1];
            $agencyInfo['contact_addr'] = $contractAddr[2];

            foreach ($express as $vo) {
                $express['name'] = $vo['0'];
                $express['number'] = $vo['1'];
            }

            $agencyId['id'] = $info['entity_id'];
            $agencyList = M('agency')->where($agencyId)->find();

            $arr = array(
                'agencyList' => $agencyList,
                'list' => $express,
                'agencyInfo' => $agencyInfo,
            );

            $this->ajaxReturn($arr);
        }
    }


    /**
     * 保存快递信息 发票 合同
     */
    public function saveExpressInfo()
    {
        if (IS_AJAX && IS_POST) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $where['id'] = I('id');
            $type = I('type');

            if ($type == 3) {
                $table = 'agency_invoice';
            } else {
                $table = 'agency_contract';
            }

            $express['expressName'] = I('expressName');
            $express['expressNumber'] = I('expressNumber');
            $data['express'] = implode(',', $express);
            $data['update_time'] = date('Y-m-d H:i:s', time());

            $result = M($table)->where($where)->save($data);

            if ($result) {
                $data['status'] = 1;
                $data['msg'] = '操作成功';
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }
        }
    }


    /**
     * 代理商审核提现申请 -- 已审核,待财务处理 || 拒绝
     */
    public function agencyAuditWithDraw()
    {
        if (IS_AJAX && IS_POST) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            $state = I('state');
            $data['state'] = $state;
            $data['memo'] = I('memo');
            $data['update_time'] = date('Y-m-d H:i:s', time());

            if ($state == Top::ApplyStateReject || $state == Top::ApplyStatePass) {
                $result = M('account_withdraw')->where($where)->save($data);

                if ($result) {
                    $data['status'] = 1;
                    $data['msg'] = '操作成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '操作失败';
                    $this->ajaxReturn($data);
                }
            }
        }
    }

    /**
     * 提现 - 财务审核
     */
    public function financeAuditWithDraw()
    {
        if (IS_AJAX && IS_POST) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));
            $state = I('state');

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            if ($state == Top::ApplyStateReject) {
                $data['state'] = $state;
                $result = M('account_withdraw')->where($where)->save($data);

                if ($result) {
                    $data['status'] = 1;
                    $data['msg'] = '操作成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '操作失败';
                    $this->ajaxReturn($data);
                }
            }

            $withDrawInfo = M('account_withdraw')->where($where)->find();
            $amount = $withDrawInfo['amount'];

            $entityId = $withDrawInfo['entity_id'];
            $agencyInfo = M('agency')->where("id = '{$entityId}'")->find();
            $accountBalance = (int)$agencyInfo['account_balance'];
            $agencyAccountState = $agencyInfo['account_state'];

            if ($agencyAccountState == Top::StateEnabled) {
                $postCode = I('code');
                $code = session('withDrawCode');

                if ($code == $postCode) {
                    session('withDrawCode', null);

                    if ($amount >= 0 && $accountBalance >= $amount && $withDrawInfo['state'] == Top::ApplyStatePass) {

                        M('agency')->startTrans();
                        try {
                            $data['state'] = I('state');
                            $data['update_time'] = date('Y-m-d H:i:s', time());
                            $data['entity_type'] = Top::EntityTypeAgency;
                            $data['operator_id'] = session('operator_id');
                            $data['sn'] = Utils::getSn();
                            $data['proof_type'] = I('proof_type');
                            $data['proof_code'] = I('proof_code');
                            $result = M('account_withdraw')->where($where)->save($data);

                            if ($data['state'] == Top::ApplyStateFinish) {
                                $agency_result = M('agency')->where("id = '{$entityId}'")->setDec('account_balance', $amount);

                                $agency_list = M('agency')->where("id = '{$entityId}'")->find();

                                $transaction_data['operator_id'] = session('operator_id');
                                $transaction_data['entity_type'] = Top::EntityTypeAgency;
                                $transaction_data['action'] = '提现';
                                $transaction_data['sn'] = Utils::getSn();
                                $transaction_data['entity_id'] = $agency_list['id'];
                                $transaction_data['account'] = $agency_list['account'];
                                $transaction_data['amount'] = '-' . $amount;
                                $transaction_data['create_time'] = date('Y-m-d H:i:s', time());
                                $transaction_data['balance'] = $agency_list['account_balance'];
                                $transaction_data['remark'] = 'top_account_withdraw.id:' . I('id');
                                $transaction_data['object_id'] = I('id');
                                $transaction_data['object_type'] = Top::ObjectTypeWithDraw;
                                $transaction_data['object_name'] = '提现';

                                $transaction_result = M('account_transaction')->add($transaction_data);
                            }

                            $template = array(
                                'touser' => $agencyInfo['weixinmp_openid'],
                                'template_id' => Utils::withDrawTemplateId(),

                                'data' => array(
                                    'first' => array('value' => urlencode("亲,您的提现申请于 " . $data['update_time'] . " 通过审核,提现成功"), 'color' => "#000"),
                                    'keyword1' => array('value' => urlencode(Utils::getYuan($amount)), 'color' => "#000"),
                                    'keyword2' => array('value' => urlencode($withDrawInfo['bank_account']), 'color' => '#000'),
                                    'keyword3' => array('value' => urlencode($withDrawInfo['create_time']), 'color' => '#000'),
                                )
                            );

                            if ($result && $agency_result && $transaction_result) {
                                M('agency')->commit();
                                $this->send_tpl($template);
                                $data['status'] = 1;
                                $data['msg'] = '操作成功';
                                $this->ajaxReturn($data);
                            } else {
                                $data['status'] = 3;
                                $data['msg'] = '操作失败';
                                $this->ajaxReturn($data);
                            }
                        } catch (Exception $ex) {
                            M('agency')->rollback();
                        }
                    } else {
                        $data['status'] = 2;
                        $data['msg'] = '对不起操作失败，提现金额大于可用余额';
                        $this->ajaxReturn($data);
                    }
                } else {
                    $data['status'] = 4;
                    $data['msg'] = '请勿重复操作';
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 2;
                $data['msg'] = '该代理商账户被冻结';
                $this->ajaxReturn($data);
            }
        }
    }

    /**
     * 提现申请
     */
    public function withdrawList()
    {
        $_SESSION['withDrawCode'] = 400;
        $state = I('state');
        $name = trim(I('names'));
        $operatorId = session('operator_id');
        $roleId = session('role_id');
        $entity_type = Top::EntityTypeAgency;
        $startTime = !empty(I('start_time')) ? I('start_time') : date("2015-05-01", time());
        $endTime = !empty(I('end_time')) ? I('end_time') : date('Y-m-d', time());

        $this->operatorData = C('SHOW_OPERATOR_DATA');

        if (strpos($this->operatorData, $roleId) !== false) {
            $this->operatorList = M('operator')->where('id != 2')->field('id,display_name')->select();
            $this->oid = !empty(I('get.oid')) ? I('get.oid') : 0;
            $operatorId = $this->oid;

            if ($this->oid == 0) {
                $operatorId = implode(',', array_column($this->operatorList, 'id'));
            }
        }

        if (!empty($name) || !empty($startTime) || !empty($endTime)) {
            if (!empty($state)) {
                $where = "operator_id in($operatorId) && entity_type = '{$entity_type}' && state = '{$state}' && (entity_name like '%%$name%%' or amount like '%%$name%%') && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
            } else {
                $where = "operator_id in($operatorId) && entity_type = '{$entity_type}' && (entity_name like '%%$name%%' or amount like '%%$name%%') && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
            }
        }

        $recordSum = M('account_withdraw')->where($where)->count(); //记录总数
        $pageInfo = Utils::pages('account_withdraw', $where, C('PAGE_SET'), $order = " id desc ");

        $this->state = $state;
        $this->total = $recordSum;
        $this->info = $pageInfo['info'];
        $this->page = $pageInfo['page'];
        $this->assign('name', $name);
        $this->assign('startTime', $startTime);
        $this->assign('endTime', $endTime);
        $this->display();
    }

    /**
     * 提现 - 查看总额
     */

    function showAccountBalance()
    {
        if (IS_AJAX && IS_POST) {
            $where['id'] = I('id');
            $info = M('agency')->where($where)->field('id,account_balance')->find();

            if ($info) {
                $data['status'] = 1;
                $data['account_balance'] = Utils::getYuan($info['account_balance']);
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '查看失败';
                $this->ajaxReturn($data);
            }
        }
    }


    public function invoiceList()
    {
        if (IS_AJAX && IS_POST) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            $agencyInvoiceInfo = M('agency_invoice')->where($where)->find();
            $invoiceDetail = $agencyInvoiceInfo['detail'];
            $entityId = $agencyInvoiceInfo['entity_id'];
            $agencyInfo = M('agency')->where("id = '{$entityId}'")->find();
            $agencyAccountState = $agencyInfo['account_state'];

            $state = I('state');
            $data['state'] = $state;
            $data['memo'] = I('memo');
            $data['proof_type'] = I('proof_type');
            $data['proof_code'] = I('proof_code');
            $data['update_time'] = date('Y-m-d H:i:s', time());

            if (!empty($data['proof_type']) && !empty($data['proof_code'])) {
                $result = M('agency_invoice')->where($where)->save($data);

                if ($result) {
                    $data['status'] = 1;
                    $data['msg'] = '操作成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '操作失败';
                    $this->ajaxReturn($data);
                }
            }

            if ($state == Top::ApplyStateReject) {
                $result = M('agency_invoice')->where($where)->save($data);

                if ($result) {
                    $data['status'] = 1;
                    $data['msg'] = '操作成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '操作失败';
                    $this->ajaxReturn($data);
                }
            }


            if ($agencyAccountState == Top::StateEnabled) {
                $data['method'] = I('method');
                $amount = Utils::getYuan($agencyInvoiceInfo['amount']);
                $amount = Utils::setServiceFeeTax($amount, $agencyInfo['operator_id'], $invoiceDetail);

                $amount = $amount + $agencyInvoiceInfo['express_fee'];
                $availableBalance = Utils::getAgencyAvailableFen($entityId);
                $postCode = I('code');
                $code = session('invoiceCode');

                if ($code == $postCode) {
                    session('invoiceCode', null);

                    if ($availableBalance >= $amount && $agencyInvoiceInfo['state'] == Top::ApplyStateWait && $state = Top::ApplyStatePass) {
                        M('agency')->startTrans();
                        try {
                            $result = M('agency_invoice')->where($where)->save($data);
                            $agencyResult = M('agency')->where("id = '{$entityId}'")->setDec('account_balance', $amount);

                            if ($agencyResult) {
                                $nowTime = Utils::getBatch();
                                $agencyInfo = M('agency')->where("id = '{$entityId}'")->find();
                                $agencyData['operator_id'] = $agencyInfo['operator_id'];
                                $agencyData['sn'] = Utils::getSn();
                                $agencyData['batch'] = $nowTime;
                                $agencyData['account'] = $agencyInfo['account'];
                                $agencyData['entity_type'] = Top::EntityTypeAgency;
                                $agencyData['entity_id'] = $agencyInfo['id'];
                                $agencyData['entity_name'] = $agencyInfo['name'];
                                $agencyData['amount'] = -$amount;
                                $agencyData['action'] = '财务服务费';
                                $agencyData['remark'] = 'top_agency_invoice.id:' . I('id');
                                $agencyData['balance'] = $agencyInfo['account_balance'];
                                $agencyData['create_time'] = date("Y-m-d H:i:s", time());
                                $agencyData['object_id'] = I('id');
                                $agencyData['object_type'] = Top::ObjectTypeInvoice;
                                $agencyData['object_name'] = '发票';

                                $agencyContractTransaction = M('account_transaction')->add($agencyData);

                                $operatorId['id'] = $agencyData['operator_id'];
                                $operatorInfo = M('operator')->where($operatorId)->find();
                                $operatorBalance = $operatorInfo['account_balance'];
                                $operatorData['account_balance'] = $operatorBalance + $amount;
                                $operatorData['update_time'] = date("Y-m-d H:i:s", time());
                                $operatorResult = M('operator')->where($operatorId)->save($operatorData);

                                $operatorTransactionData['operator_id'] = $agencyInfo['operator_id'];
                                $operatorTransactionData['sn'] = Utils::getSn();
                                $operatorTransactionData['batch'] = $nowTime;
                                $operatorTransactionData['account'] = $operatorInfo['account'];
                                $operatorTransactionData['entity_type'] = Top::EntityTypeOperator;
                                $operatorTransactionData['entity_id'] = $operatorInfo['id'];
                                $operatorTransactionData['action'] = '财务服务收入';
                                $operatorTransactionData['remark'] = 'top_agency_invoice.id:' . I('id');
                                $operatorTransactionData['amount'] = $amount;
                                $operatorTransactionData['balance'] = $operatorData['account_balance'];
                                $operatorTransactionData['create_time'] = date("Y-m-d H:i:s", time());
                                $operatorTransactionData['object_id'] = I('id');
                                $operatorTransactionData['object_type'] = Top::ObjectTypeInvoice;
                                $operatorTransactionData['object_name'] = '发票';

                                $operatorTransactionResult = M('account_transaction')->add($operatorTransactionData);
                            }

                            if ($result && $agencyResult && $agencyContractTransaction && $operatorResult && $operatorTransactionResult) {
                                M('agency')->commit();
                                $data['status'] = 1;
                                $data['msg'] = '操作成功';
                                $this->ajaxReturn($data);
                            } else {
                                $data['status'] = 2;
                                $data['msg'] = '操作失败';
                                $this->ajaxReturn($data);
                            }
                        } catch (Exception $ex) {
                            M('agency')->rollback();
                        }
                    } else {
                        $data['status'] = 3;
                        $data['msg'] = '操作失败，代理商可用余额不足支付此次申请';
                        $this->ajaxReturn($data);
                    }
                } else {
                    $data['status'] = 4;
                    $data['msg'] = '请勿重复提交';
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 3;
                $data['msg'] = '该代理商账户被冻结';
                $this->ajaxReturn($data);
            }
        } else {
            $_SESSION['invoiceCode'] = 400;
            $name = trim(I('names'));
            $operatorId = session('operator_id');
            $roleId = session('role_id');
            $entity_type = Top::EntityTypeAgency;
            $startTime = !empty(I('start_time')) ? I('start_time') : date("2015-05-01", time());
            $endTime = !empty(I('end_time')) ? I('end_time') : date('Y-m-d', time());

            $this->operatorData = C('SHOW_OPERATOR_DATA');

            if (strpos($this->operatorData, $roleId) !== false) {
                $this->operatorList = M('operator')->where('id != 2')->field('id,display_name')->select();
                $this->oid = !empty(I('get.oid')) ? I('get.oid') : 0;
                $operatorId = $this->oid;

                if ($this->oid == 0) {
                    $operatorId = implode(',', array_column($this->operatorList, 'id'));
                }
            }

            if (!empty($name) || !empty($startTime) || !empty($endTime)) {
                $where = "operator_id in($operatorId) && entity_type = '{$entity_type}' && entity_name like '%%$name%%' && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
            }

            $pageInfo = Utils::pages('agency_invoice', $where, C('PAGE_SET'), $order = " id desc ");
            $this->info = $pageInfo['info'];
            $this->page = $pageInfo['page'];
            $this->assign('name', $name);
            $this->assign('startTime', $startTime);
            $this->assign('endTime', $endTime);

            $this->display();
        }
    }


    public function contractList()
    {
        if (IS_AJAX && IS_POST) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }
            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            $agencyContractInfo = M('agency_contract')->where($where)->find();
            $entityId = $agencyContractInfo['entity_id'];
            $agencyInfo = M('agency')->where("id = '{$entityId}'")->find();
            $agencyAccountState = $agencyInfo['account_state'];

            $state = I('state');
            $data['state'] = $state;
            $data['memo'] = I('memo');
            $data['proof_type'] = I('proof_type');
            $data['proof_code'] = I('proof_code');
            $data['update_time'] = date('Y-m-d H:i:s', time());

            if (!empty($data['proof_type']) && !empty($data['proof_code'])) {
                $result = M('agency_contract')->where($where)->save($data);

                if ($result) {
                    $data['status'] = 1;
                    $data['msg'] = '操作成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 2;
                    $data['msg'] = '操作失败';
                    $this->ajaxReturn($data);
                }
            }

            if ($state == Top::ApplyStateReject) {
                $result = M('agency_contract')->where($where)->save($data);

                if ($result) {
                    $data['status'] = 1;
                    $data['msg'] = '操作成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 2;
                    $data['msg'] = '操作失败';
                    $this->ajaxReturn($data);
                }
            }

            if ($agencyAccountState == Top::StateEnabled) {
                $postCode = I('code');
                $code = session('contractCode');

                if ($code == $postCode) {
                    session('contractCode', null);
                    $inland = $agencyContractInfo['inland_count'];
                    $outbound = $agencyContractInfo['outbound_count'];
                    $peritem = $agencyContractInfo['peritem_count'];
                    $totalNumber = $inland + $outbound + $peritem;
                    $contractFee = $agencyContractInfo['contract_fee'];
                    $totalMoney = $totalNumber * $contractFee;
                    $totalMoney = $totalMoney + $agencyContractInfo['express_fee'];

                    $availableBalance = Utils::getAgencyAvailableFen($agencyInfo['id']);

                    if (($availableBalance >= $totalMoney) && $totalMoney > 0 && $agencyContractInfo['state'] == Top::ApplyStateWait) {
                        M('agency')->startTrans();
                        try {
                            $result = M('agency_contract')->where($where)->save($data);

                            if ($state == Top::ApplyStatePass) {
                                $nowTime = Utils::getBatch();
                                $agencyId['id'] = $agencyInfo['id'];
                                $agencyResult = M('agency')->where($agencyId)->setDec('account_balance', $totalMoney);

                                $agencyInfo = M('agency')->where($agencyId)->find();
                                $agencyData['operator_id'] = $agencyInfo['operator_id'];
                                $agencyData['sn'] = Utils::getSn();
                                $agencyData['batch'] = $nowTime;
                                $agencyData['account'] = $agencyInfo['account'];
                                $agencyData['entity_type'] = Top::EntityTypeAgency;
                                $agencyData['entity_id'] = $agencyInfo['id'];
                                $agencyData['entity_name'] = $agencyInfo['name'];
                                $agencyData['amount'] = -$totalMoney;
                                $agencyData['action'] = '购买合同';
                                $agencyData['balance'] = $agencyInfo['account_balance'];
                                $agencyData['remark'] = 'top_agency_contract.id:' . I('id');
                                $agencyData['create_time'] = date("Y-m-d H:i:s", time());
                                $agencyData['object_id'] = I('id');
                                $agencyData['object_type'] = Top::ObjectTypeContact;
                                $agencyData['object_name'] = '合同';

                                $agencyContractTransaction = M('account_transaction')->add($agencyData);

                                $operatorId['id'] = $agencyData['operator_id'];
                                $operatorInfo = M('operator')->where($operatorId)->find();
                                $operatorBalance = $operatorInfo['account_balance'];
                                $operatorData['account_balance'] = $operatorBalance + $totalMoney;
                                $operatorData['update_time'] = date("Y-m-d H:i:s", time());
                                $operatorResult = M('operator')->where($operatorId)->save($operatorData);

                                $operatorTransactionData['operator_id'] = $agencyInfo['operator_id'];
                                $operatorTransactionData['sn'] = Utils::getSn();
                                $operatorTransactionData['batch'] = $nowTime;
                                $operatorTransactionData['account'] = $operatorInfo['account'];
                                $operatorTransactionData['entity_type'] = Top::EntityTypeOperator;
                                $operatorTransactionData['entity_id'] = $operatorInfo['id'];
                                $operatorTransactionData['action'] = '合同销售收入';
                                $operatorTransactionData['amount'] = $totalMoney;
                                $operatorTransactionData['balance'] = $operatorData['account_balance'];
                                $operatorTransactionData['remark'] = 'top_agency_contract.id:' . I('id');
                                $operatorTransactionData['create_time'] = date("Y-m-d H:i:s", time());
                                $operatorTransactionData['object_id'] = I('id');
                                $operatorTransactionData['object_type'] = Top::ObjectTypeContact;
                                $operatorTransactionData['object_name'] = '合同';

                                $operatorTransactionResult = M('account_transaction')->add($operatorTransactionData);
                            }

                            if ($result && $agencyResult && $agencyContractTransaction && $operatorResult && $operatorTransactionResult) {
                                M('agency')->commit();
                                $data['status'] = 1;
                                $data['msg'] = '操作成功';
                                $this->ajaxReturn($data);
                            } else {
                                $data['status'] = 3;
                                $data['msg'] = '操作失败';
                                $this->ajaxReturn($data);
                            }
                        } catch (Exception $ex) {
                            M('agency')->rollback();
                        }
                    } else {
                        $data['status'] = 2;
                        $data['msg'] = '操作失败，代理商可用余额不足支付此次申请';
                        $this->ajaxReturn($data);
                    }
                } else {
                    $data['status'] = 4;
                    $data['msg'] = '请勿重复操作';
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 2;
                $data['msg'] = '该代理商账户被冻结';
                $this->ajaxReturn($data);
            }
        } else {
            $_SESSION['contractCode'] = 400;
            $name = trim(I('names'));
            $operatorId = session('operator_id');
            $roleId = session('role_id');
            $entity_type = Top::EntityTypeAgency;
            $startTime = !empty(I('start_time')) ? I('start_time') : date("2015-05-01", time());
            $endTime = !empty(I('end_time')) ? I('end_time') : date('Y-m-d', time());

            $this->operatorData = C('SHOW_OPERATOR_DATA');

            if (strpos($this->operatorData, $roleId) !== false) {
                $this->operatorList = M('operator')->where('id != 2')->field('id,display_name')->select();
                $this->oid = !empty(I('get.oid')) ? I('get.oid') : 0;
                $operatorId = $this->oid;

                if ($this->oid == 0) {
                    $operatorId = implode(',', array_column($this->operatorList, 'id'));
                }
            }

            if (!empty($name) || !empty($startTime) || !empty($endTime)) {
                $where = "operator_id in($operatorId) && entity_type = '{$entity_type}' && entity_name like '%%$name%%' && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
            }

            $pageInfo = Utils::pages('agency_contract', $where, C('PAGE_SET'), $order = " id desc ");

            $this->info = $pageInfo['info'];
            $this->page = $pageInfo['page'];
            $this->assign('name', $name);
            $this->assign('startTime', $startTime);
            $this->assign('endTime', $endTime);

            $this->display();
        }
    }


}
